package com.TP.www.service.impl;

import com.TP.www.dao.impl.*;
import com.TP.www.po.Cart;
import com.TP.www.po.CustomerCoupon;
import com.TP.www.po.Good;
import com.TP.www.po.User;
import com.TP.www.service.CartPort;

import java.util.List;

import static com.TP.www.constant.Constant.*;

/**
 * @author 邱彦祥
 * 购物车功能实现类
 */
public class CartImpl implements CartPort {
    CartDAO cartDAO = new CartDAO();
    CustomerCouponDAO customerCouponDAO = new CustomerCouponDAO();
    GoodDAO goodDAO = new GoodDAO();
    OrderDAO orderDAO = new OrderDAO();
    CustomerDAO customerDAO = new CustomerDAO();

    @Override
    public int add(User user, Good good, int num){
            String sql = "insert into cart (goodsNum, User_Cart_Id, Goods_Cart_Id) values (?,?,?);";
            return cartDAO.executeUpdate(sql,num,user.getId(),good.getId());
    }


    @Override
    public boolean order(User user, Cart cart){
        List<CustomerCoupon> customerCoupons = customerCouponDAO.executeQueryF(GET_COUPON_FOR_CUSTOMER,loginUser.getId());
        CustomerCoupon usefulCoupon = null;
        int max = 0;
        Double totalNum = cart.getPrice()*cart.getGoodsNum();
        Double disNum = 0.0;
        for(CustomerCoupon customerCoupon:customerCoupons){
            if(customerCoupon.getInitialNum() >= max && customerCoupon.getStoreName().equals(cart.getStoreName())){
                usefulCoupon = customerCoupon;
            }
        }
        if (usefulCoupon != null){
            totalNum -= usefulCoupon.getOffNum();
            disNum = usefulCoupon.getOffNum();
        }
        if(user.getAsset() < totalNum){
            System.out.println("账户余额不足!请充值后再进行下单!");
            System.out.println("按任意键返回...");
            SYS_SC.nextLine();
            return false;
        }
        int goodsOrdersId = goodDAO.executeQuery(GET_GOOD_ID,cart.getGoodName(),cart.getStoreName()).get(0).getId();
        orderDAO.executeUpdate(ADD_ORDER,user.getId(),goodsOrdersId,cart.getGoodsNum(),cart.getPrice(),disNum,totalNum,-1);
        cartDAO.executeUpdate(DELETE_CART_FOR_ID,cart.getId());
        loginUser.setAsset(loginUser.getAsset()-totalNum);
        customerDAO.executeUpdate(UPDATE_CUSTOMER_ASSET,loginUser.getAsset()-totalNum,loginUser.getId());
        if(usefulCoupon != null){
            customerCouponDAO.executeUpdate(DELETE_CUSTOMER_COUPON_BY_CUSTOMER_COUPON_ID,usefulCoupon.getCustomerCouponId());
        }
        System.out.println("下单成功");
        System.out.println("按任意键返回...");
        SYS_SC.nextLine();
        return true;
    }


    @Override
    public boolean delete(Cart cart){
            return cartDAO.executeUpdate(DELETE_CART_FOR_ID, cart.getId()) > 0;
    }
}
